package com.intelligentmeterreadingsys.httpserver;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpDownload {
    private URL url = null;

    /**
     * 下载文本文件
     * 
     * @param urlstr
     * @return
     */
    public String download(String urlstr) {

	String line = null;
	BufferedReader buffer = null;
	try {
	    url = new URL(urlstr);// 创建URL对象
	    HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();// 创建HTTP连接
	    InputStreamReader isr = new InputStreamReader(urlcon.getInputStream());// 通过连接获取流
	    buffer = new BufferedReader(isr);
	    while (buffer.readLine() != null) {
		line = line + buffer.readLine();
	    }
	} catch (MalformedURLException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} finally {
	    try {
		buffer.close();
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	return line;

    }

    /**
     * 下载文件
     * 
     * @param urlstr
     *            下载地址
     * @param path
     *            下载后保存位置
     * @param filename
     *            文件名
     * @return int 0代表下载成功
     */
    public int downFile(String urlstr, String path, String filename) {

	InputStream is = null;
	FileUtil fileutil = new FileUtil();
	if (fileutil.isFileExist(path + "/" + filename)) {
	    return 1;
	} else {
	    try {
		url = new URL(urlstr);
		HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();// 创建HTTP连接
		is = urlcon.getInputStream();

		File file = fileutil.writeSD(path, filename, is);
		if (file == null) {
		    return -1;
		}
	    } catch (MalformedURLException e) {

		e.printStackTrace();
	    } catch (IOException e) {

		e.printStackTrace();
	    } finally {
		try {
		    is.close();
		} catch (IOException e) {

		    e.printStackTrace();
		}
	    }

	}
	return 0;

    }

    public int DownImage(String url, String filepath, String filename) {
	int i = 1;
	InputStream is = null;
	try {
	    is = getImageStream(url);
	    // byte[] data = readStream(is);
	    // Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
	    // data.length);// bitmap
	    // System.out.println("filepath" + filepath);
	    Bitmap bitmap = BitmapFactory.decodeStream(is);

	    saveFile(bitmap, filename, filepath);
	    return 0;
	} catch (Exception e) {

	    e.printStackTrace();
	    return 1;
	} finally {
	    if (is != null) {
		try {
		    is.close();
		} catch (IOException e) {

		    e.printStackTrace();
		}
	    }
	}
    }

    /**
     * Get image from newwork
     * 
     * @param path
     *            The path of image
     * @return byte[]
     * @throws Exception
     */
    public byte[] getImage(String path) throws Exception {
	URL url = new URL(path);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setConnectTimeout(5 * 1000);
	conn.setRequestMethod("GET");
	InputStream inStream = conn.getInputStream();
	if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
	    return readStream(inStream);
	}
	return null;
    }

    /**
     * Get image from newwork
     * 
     * @param path
     *            The path of image
     * @return InputStream
     * @throws Exception
     */
    public InputStream getImageStream(String path) throws Exception {
	System.out.println(path);
	URL url = new URL(path);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	conn.setConnectTimeout(5 * 1000);
	conn.setRequestMethod("POST");
	if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
	    return conn.getInputStream();
	}
	return null;
    }

    /**
     * Get data from stream
     * 
     * @param inStream
     * @return byte[]
     * @throws Exception
     */
    public static byte[] readStream(InputStream inStream) throws Exception {
	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
	byte[] buffer = new byte[1024];
	int len = 0;
	while ((len = inStream.read(buffer)) != -1) {
	    outStream.write(buffer, 0, len);
	}

	outStream.close();
	inStream.close();
	return outStream.toByteArray();
    }

    /**
     * 保存文件
     * 
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName, String path) throws IOException {
	File dirFile = new File(path);
	if (!dirFile.exists()) {
	    dirFile.mkdir();
	}
	System.out.println(path + "path");
	File myCaptureFile = new File(path + "/" + fileName);
	if (!myCaptureFile.exists()) {
	    myCaptureFile.createNewFile();
	}
	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
	bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
	bos.flush();
	bos.close();
    }

    /**
     * 下载图片
     * 
     * @param path
     * @param url
     * @return
     */
    public synchronized Bitmap getBitMap(String path, String fileName, String url) {
	URL myFileUrl = null;
	Bitmap bitmap = null;

	try {
	    myFileUrl = new URL(url);
	    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
	    conn.setConnectTimeout(5 * 1000);
	    conn.setRequestMethod("POST");
	    conn.setDoInput(true);
	    conn.connect();
	    InputStream is = conn.getInputStream();
	    int length = (int) conn.getContentLength();
	    if (length != -1) {
		byte[] imgData = new byte[length];
		byte[] temp = new byte[512];
		int readLen = 0;
		int destPos = 0;
		while ((readLen = is.read(temp)) > 0) {
		    System.arraycopy(temp, 0, imgData, destPos, readLen);
		    destPos += readLen;
		}
		bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
	    }
	} catch (MalformedURLException e) {
	    e.printStackTrace();

	} catch (IOException e) {

	    e.printStackTrace();
	}
	return bitmap;

    }
}
